import { Toast } from "vant";

export default {
  /**
   * 初始化微信支付
   * @param {Object} payParams 支付参数
   * @returns {Promise}
   */
  pay(payParams) {
    console.log(payParams,'payParams')
    return new Promise((resolve, reject) => {
      if (typeof WeixinJSBridge === "undefined") {
        Toast.fail("请在微信中打开页面");
        reject(new Error("WeixinJSBridge未定义"));
        return;
      }

      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: "wxf6b22350d8075054",
          timeStamp: payParams.timeStamp,
          nonceStr: payParams.nonceStr,
          package: payParams.package,
          signType: payParams.signType,
          paySign: payParams.paySign,
        },
        (res) => {
          if (res.err_msg === "get_brand_wcpay_request:ok") {
            resolve(true); // 支付成功
          } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
            Toast("您已取消支付");
            resolve(false); // 用户取消
          } else {
            Toast.fail("支付失败: " + res.err_msg);
            reject(new Error(res.err_msg)); // 支付失败
          }
        }
      );
    });
  },

  /**
   * 检查是否在微信环境
   * @returns {boolean}
   */
  isWechat() {
    const ua = window.navigator.userAgent.toLowerCase();
    return ua.includes("micromessenger");
  },
};
